<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>我的订单 - 家电维修系统</title>
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <script th:src="@{/js/bootstrap.bundle.min.js}"></script>

    <style>
        body {
            background-color: #f8f9fa;
        }
        .order-container {
            max-width: 1000px;
            margin: 50px auto;
            padding: 20px;
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .order-card {
            margin-bottom: 20px;
            cursor: pointer;
        }
        .order-card:hover {
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        #map {
            height: 300px;
            width: 100%;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/">家电维修系统</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/orders">我的订单</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/profile">个人资料</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/announcements">公告</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/forum">论坛</a>
                    </li>
                </ul>
                <div class="d-flex">
                    <span class="navbar-text me-3" id="userInfo"></span>
                    <button class="btn btn-outline-light" onclick="logout()">退出</button>
                </div>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="order-container">
            <h2 class="text-center mb-4">我的订单</h2>
            
            <div class="row">
                <div class="col-md-8">
                    <div id="orderList"></div>
                </div>
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title mb-0">订单状态统计</h5>
                        </div>
                        <div class="card-body">
                            <div id="statusStats"></div>
                        </div>
                    </div>

                    <div class="card mt-4">
                        <div class="card-header">
                            <h5 class="card-title mb-0">在线维修工位置</h5>
                        </div>
                        <div class="card-body">
                            <div id="onlineMap" style="height: 400px;"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
    <script type="text/javascript" src="https://api.map.baidu.com/api?type=webgl&v=1.0&ak=spEZ8x14LoDN10ejoQD7GdxOEJYOwqcw"></script>
    <script src="/js/request.js"></script>
    <script>
        let orderMap = null;  // 订单详情中的地图
        let onlineMap = null; // 在线维修工地图
        let currentUser = null;
        let currentOrder = null;
        let repairmanMarker = null;
        let trackingInterval = null;
        let polyline = null;
        let onlineRepairmen = [];  // 在线维修工标记数组
        let userLocation = { lat: 39.900, lng: 116.400 }; // 模拟用户位置

        // 模拟的维修工数据
        const mockRepairmen = [
            { id: 1, name: "张师傅", lat: 39.915, lng: 116.404, status: "空闲" },
            { id: 2, name: "李师傅", lat: 39.925, lng: 116.414, status: "工作中" },
            { id: 3, name: "王师傅", lat: 39.905, lng: 116.394, status: "空闲" },
            { id: 4, name: "赵师傅", lat: 39.935, lng: 116.424, status: "工作中" },
            { id: 5, name: "刘师傅", lat: 39.895, lng: 116.384, status: "空闲" }
        ];

        // 计算两点之间的直线距离（公里）
        function calculateDistance(lat1, lon1, lat2, lon2) {
            const R = 6371; // 地球半径，单位公里
            const dLat = (lat2 - lat1) * Math.PI / 180; 
            const dLon = (lon2 - lon1) * Math.PI / 180;
            const a =
                0.5 - Math.cos(dLat) / 2 +
                Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
                (1 - Math.cos(dLon)) / 2;
            return R * 2 * Math.asin(Math.sqrt(a));
        }

        // 初始化在线维修工地图
        function initOnlineMap() {
            onlineMap = new BMapGL.Map("onlineMap");
            const point = new BMapGL.Point(116.404, 39.915);
            onlineMap.centerAndZoom(point, 12);
            onlineMap.enableScrollWheelZoom(true);
            onlineMap.setTilt(45);

            let closestRepairmanMarker = null;
            let minDistance = Infinity;

            // 添加维修工标记
            mockRepairmen.forEach(repairman => {
                const point = new BMapGL.Point(repairman.lng, repairman.lat);
                const distance = calculateDistance(userLocation.lat, userLocation.lng, repairman.lat, repairman.lng);

                const marker = new BMapGL.Marker(point, {
                    icon: new BMapGL.Icon("/images/worker.svg", new BMapGL.Size(32, 32), {
                        offset: new BMapGL.Size(16, 32),
                        imageOffset: new BMapGL.Size(0, 0)
                    }),
                    title: repairman.name
                });

                if (distance < minDistance) { // This block was added by a previous toolcall
                    minDistance = distance;
                    closestRepairmanMarker = marker;
                }
                
                // 添加信息窗口
                const distanceText = distance.toFixed(2) + ' km';
                const infoWindowContent = `
                    <div style="padding: 10px;">
                        <h6>${repairman.name}</h6>
                        <p>状态：<span class="badge ${repairman.status === '空闲' ? 'bg-success' : 'bg-warning'}">${repairman.status}</span></p>
                        <p>距离您：${distanceText}</p>
                    </div>`;
                const infoWindowOpts = {
                    width: 250,
                    height: 150, 
                    title: "维修工信息"
                };
                const infoWindow = new BMapGL.InfoWindow(infoWindowContent, infoWindowOpts);
                
                marker.addEventListener('click', function() {
                    onlineMap.openInfoWindow(infoWindow, point);
                });

                onlineMap.addOverlay(marker);
                onlineRepairmen.push(marker);

                // 随机移动维修工位置
                setInterval(() => {
                    const newLat = repairman.lat + (Math.random() - 0.5) * 0.01;
                    const newLng = repairman.lng + (Math.random() - 0.5) * 0.01;
                    const newPoint = new BMapGL.Point(newLng, newLat);
                    marker.setPosition(newPoint);
                }, 5000);
            });

            // 设置最近维修工的图标
            if (closestRepairmanMarker) {
                closestRepairmanMarker.setIcon(new BMapGL.Icon("/images/worker_closest.svg", new BMapGL.Size(38, 38), { // 图标可以稍微大一点以示突出
                    offset: new BMapGL.Size(19, 38), // 偏移量也相应调整
                    imageOffset: new BMapGL.Size(0, 0)
                }));
            }
        }

        // 初始化订单地图
        function initOrderMap(mapContainer) {
            orderMap = new BMapGL.Map(mapContainer);
            const point = new BMapGL.Point(116.404, 39.915);
            orderMap.centerAndZoom(point, 12);
            orderMap.enableScrollWheelZoom(true);
            orderMap.setTilt(60);
            return orderMap;
        }

        // 模拟维修工位置移动
        function simulateRepairmanMovement(startPoint, endPoint) {
            if (trackingInterval) {
                clearInterval(trackingInterval);
            }
            
            // 清除之前的标记和路线
            if (repairmanMarker) {
                orderMap.removeOverlay(repairmanMarker);
            }
            if (polyline) {
                orderMap.removeOverlay(polyline);
            }

            // 创建起点和终点标记
            const startMarker = new BMapGL.Marker(startPoint, {
                icon: new BMapGL.Icon("/images/worker.svg", new BMapGL.Size(32, 32), {
                    offset: new BMapGL.Size(16, 32),
                    imageOffset: new BMapGL.Size(0, 0)
                }),
                title: "维修工起始位置"
            });
            const endMarker = new BMapGL.Marker(endPoint, {
                icon: new BMapGL.Icon("/images/home.svg", new BMapGL.Size(32, 32), {
                    offset: new BMapGL.Size(16, 32),
                    imageOffset: new BMapGL.Size(0, 0)
                }),
                title: "维修地址"
            });
            orderMap.addOverlay(startMarker);
            orderMap.addOverlay(endMarker);

            // 创建维修工标记
            repairmanMarker = new BMapGL.Marker(startPoint, {
                icon: new BMapGL.Icon("/images/worker_moving.svg", new BMapGL.Size(32, 32), {
                    offset: new BMapGL.Size(16, 32),
                    imageOffset: new BMapGL.Size(0, 0)
                }),
                title: "维修工实时位置"
            });
            orderMap.addOverlay(repairmanMarker);

            // 计算路线点
            const points = [];
            const numPoints = 50;
            for (let i = 0; i <= numPoints; i++) {
                const lat = startPoint.lat + (endPoint.lat - startPoint.lat) * (i / numPoints);
                const lng = startPoint.lng + (endPoint.lng - startPoint.lng) * (i / numPoints);
                points.push(new BMapGL.Point(lng, lat));
            }

            // 创建轨迹线
            polyline = new BMapGL.Polyline(points, {
                strokeColor: "#18a45b",
                strokeWeight: 4,
                strokeOpacity: 0.8
            });
            orderMap.addOverlay(polyline);

            let currentIndex = 0;
            trackingInterval = setInterval(() => {
                if (currentIndex >= points.length) {
                    clearInterval(trackingInterval);
                    return;
                }
                repairmanMarker.setPosition(points[currentIndex]);
                currentIndex++;
            }, 1000);

            // 调整视图以显示整个路线
            orderMap.setViewport(points);
        }

        // 获取用户信息
        function getUserInfo() {
            if (!checkLoginStatus()) return;

            $.ajax({
                url: '/api/user/profile',
                type: 'GET',
                success: function(response) {
                    currentUser = response;
                    $('#userInfo').text('欢迎，' + response.realName);
                    loadOrders();
                }
            });
        }

        // 加载订单列表
        function loadOrders() {
            if (!currentUser || !currentUser.id) return;

            $.ajax({
                url: '/api/order/user/' + currentUser.id,
                type: 'GET',
                success: function(orders) {
                    const orderList = $('#orderList');
                    orderList.empty();
                    
                    // 统计订单状态
                    const statusStats = {
                        0: 0, // 待接单
                        1: 0, // 已接单
                        2: 0, // 维修中
                        3: 0, // 已完成
                        4: 0  // 已取消
                    };

                    orders.forEach(order => {
                        statusStats[order.status]++;
                        
                        orderList.append(`
                            <div class="card order-card" onclick="showOrderDetail(${order.id})">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h5 class="card-title">${order.applianceType}</h5>
                                        <span class="badge bg-${getStatusBadgeColor(order.status)}">
                                            ${getStatusText(order.status)}
                                        </span>
                                    </div>
                                    <p class="card-text">故障描述：${order.description}</p>
                                    <p class="card-text">维修地址：${order.address}</p>
                                    <p class="card-text">预约时间：${new Date(order.appointmentTime).toLocaleString()}</p>
                                    ${order.repairmanId ? `
                                        <p class="card-text">维修工：${order.repairmanName || '未知'}</p>
                                    ` : ''}
                                </div>
                            </div>
                        `);
                    });

                    // 显示状态统计
                    const statusStatsHtml = `
                        <div class="list-group">
                            <div class="list-group-item d-flex justify-content-between align-items-center">
                                待接单
                                <span class="badge bg-primary rounded-pill">${statusStats[0]}</span>
                            </div>
                            <div class="list-group-item d-flex justify-content-between align-items-center">
                                已接单
                                <span class="badge bg-info rounded-pill">${statusStats[1]}</span>
                            </div>
                            <div class="list-group-item d-flex justify-content-between align-items-center">
                                维修中
                                <span class="badge bg-warning rounded-pill">${statusStats[2]}</span>
                            </div>
                            <div class="list-group-item d-flex justify-content-between align-items-center">
                                已完成
                                <span class="badge bg-success rounded-pill">${statusStats[3]}</span>
                            </div>
                            <div class="list-group-item d-flex justify-content-between align-items-center">
                                已取消
                                <span class="badge bg-danger rounded-pill">${statusStats[4]}</span>
                            </div>
                        </div>
                    `;
                    $('#statusStats').html(statusStatsHtml);
                }
            });
        }

        // 清理资源
        function cleanup() {
            if (trackingInterval) {
                clearInterval(trackingInterval);
                trackingInterval = null;
            }
            if (repairmanMarker) {
                orderMap.removeOverlay(repairmanMarker);
                repairmanMarker = null;
            }
            if (polyline) {
                orderMap.removeOverlay(polyline);
                polyline = null;
            }
            currentOrder = null;
        }

        // 显示订单详情
        function showOrderDetail(orderId) {
            if (currentOrder) {
                return;
            }

            $.ajax({
                url: '/api/order/' + orderId,
                type: 'GET',
                success: function(order) {
                    currentOrder = order;
                    
                    // 显示订单详情对话框
                    const dialog = $(`
                        <div class="modal fade" id="orderDetailModal" tabindex="-1">
                            <div class="modal-dialog modal-lg">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title">订单详情</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                    </div>
                                    <div class="modal-body">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <p><strong>家电类型：</strong>${order.applianceType}</p>
                                                <p><strong>故障描述：</strong>${order.description}</p>
                                                <p><strong>维修地址：</strong>${order.address}</p>
                                                <p><strong>预约时间：</strong>${new Date(order.appointmentTime).toLocaleString()}</p>
                                                ${order.repairmanId ? `
                                                    <p><strong>维修工：</strong>${order.repairmanName || '未知'}</p>
                                                    <p><strong>联系电话：</strong>${order.repairmanPhone || '未知'}</p>
                                                ` : ''}
                                            </div>
                                            <div class="col-md-6">
                                                ${order.status === 1 || order.status === 2 ? `
                                                    <div class="card">
                                                        <div class="card-header">
                                                            <h6 class="card-title mb-0">维修工位置</h6>
                                                        </div>
                                                        <div class="card-body">
                                                            <div id="orderMap" style="height: 300px;"></div>
                                                        </div>
                                                    </div>
                                                ` : ''}
                                            </div>
                                        </div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                                        ${order.status === 1 ? `
                                            <button type="button" class="btn btn-success" onclick="simulatePayment(${order.id})">
                                                支付
                                            </button>
                                        ` : ''}
                                        ${order.status === 0 || order.status === 1 ? `
                                            <button type="button" class="btn btn-danger" onclick="cancelOrder(${order.id})">
                                                取消订单
                                            </button>
                                        ` : ''}
                                    </div>
                                </div>
                            </div>
                        </div>
                    `);
                    dialog.modal('show');
                    
                    // 如果是已接单或维修中状态，初始化地图并显示位置
                    if (order.status === 1 || order.status === 2) {
                        dialog.on('shown.bs.modal', function() {
                            // 初始化订单详情中的地图
                            initOrderMap("orderMap");
                            
                            // 模拟维修工初始位置（距离订单位置2公里）
                            const orderPoint = new BMapGL.Point(order.longitude, order.latitude);
                            const repairmanPoint = new BMapGL.Point(
                                order.longitude + 0.02,
                                order.latitude + 0.02
                            );
                            
                            // 启动位置模拟
                            simulateRepairmanMovement(repairmanPoint, orderPoint);
                        });
                    }
                    
                    dialog.on('hidden.bs.modal', function() {
                        cleanup();
                        $(this).remove();
                    });
                }
            });
        }

        // 模拟支付
        function simulatePayment(orderId) {
            alert('订单支付成功！');
            // 这里可以根据需要添加关闭模态框或刷新订单列表的逻辑
            $('#orderDetailModal').modal('hide');
            loadOrders();
        }

        // 取消订单
        function cancelOrder(orderId) {
            if (confirm('确定要取消该订单吗？')) {
                $.ajax({
                    url: '/api/order/' + orderId,
                    type: 'DELETE',
                    success: function() {
                        alert('订单已取消！');
                        $('#orderDetailModal').modal('hide');
                        currentOrder = null;
                        loadOrders();
                    },
                    error: function(xhr) {
                        alert('取消订单失败：' + xhr.responseText);
                    }
                });
            }
        }

        // 获取状态文本
        function getStatusText(status) {
            const statusMap = {
                0: '待接单',
                1: '已接单',
                2: '维修中',
                3: '已完成',
                4: '已取消'
            };
            return statusMap[status] || '未知状态';
        }

        // 获取状态徽章颜色
        function getStatusBadgeColor(status) {
            const colorMap = {
                0: 'primary',
                1: 'info',
                2: 'warning',
                3: 'success',
                4: 'danger'
            };
            return colorMap[status] || 'secondary';
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('token');
            window.location.href = '/login';
        }

        // 页面加载完成后初始化
        $(document).ready(function() {
            if (checkLoginStatus()) {
                initOnlineMap();
                getUserInfo();
            }
        });
    </script>
</body>
</html>